package com.cci.kangdao.wechatOrder.service.impl;

import com.cci.kangdao.azureAD.ManagementToken;
import com.cci.kangdao.crmapi.CRMHttpClientUtil;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.utilTool.HttpUtils;
import com.cci.kangdao.utilTool.PropertiesUtil;
import com.cci.kangdao.wechatOrder.dto.request.WeChatJsConfigRequest;
import com.cci.kangdao.wechatOrder.exception.NotCheckException;
import com.cci.kangdao.wechatOrder.model.wx.JsTicket;
import com.cci.kangdao.wechatOrder.model.wx.PushMessage;
import com.cci.kangdao.wechatOrder.model.wx.WxAppInfo;
import com.cci.kangdao.wechatOrder.model.wx.WxResult;
import com.cci.kangdao.wechatOrder.service.IWxChatSdkService;
import com.cci.kangdao.wechatOrder.util.wxsdk.WxUtils;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 微信服务实现类
 * @author: zyf
 * @create: 2021-03-11
 */
@Service
public class WxChatSdkServiceImpl implements IWxChatSdkService {
    private Logger log = Logger.getLogger(this.getClass().getName());
    @Resource
    private RedisClientUtils redisClientUtils;


    @Override
    public String getToken(Long source) throws Exception{

        WxAppInfo appInfo = WxUtils.getWxAppInfo(source.intValue());
        if (appInfo==null){
            //throw new Exception("未获取微信基础参数");
            log.error("getToken未获取微信基础参数");
            return "";
        }
        if (source == 3) {
            //调用其他服务获取token，防止  本服务和其他服务相同调用
            String urlAndParam = PropertiesUtil.getProperties("projectconfig.properties", "dcecServerUrl");
            String sign = PropertiesUtil.getProperties("projectconfig.properties", "dcecServerUrlsign");
            HashMap<String, Object> param = new HashMap<>();
            param.put("sign", sign);
            JSONObject jsonObject = CRMHttpClientUtil.httpGETRequest(urlAndParam, null, param);
            if (null != jsonObject.get("msg") && "ok".equals(jsonObject.get("msg"))) {
                if (null != jsonObject.get("accessToken") && StringUtils.isNotBlank(jsonObject.getString("accessToken"))) {
                    String ttl = jsonObject.getString("ttl");
                    Integer time = Integer.valueOf(ttl);
                    if (time > 0) {
                        redisClientUtils.set(source + "ACCESSTOKEN", jsonObject.getString("accessToken"), time);
                    }
                    return jsonObject.getString("accessToken");
                }
            } else {
                log.error("getToken未获取到token数据");
                return "";
            }
        }
        //获取微信TOKEn
        ManagementToken token = WxUtils.getToken(appInfo.getAppId(),appInfo.getSecret());
        if (token== null){
            //throw new Exception("获取微信TOKEN失败");
            log.error("getToken获取微信TOKEN失败");
            return "";
        }
        redisClientUtils.set(source+"ACCESSTOKEN",token.getAccessToken(),60*60);

        return token.getAccessToken();
    }

    @Override
    public WxResult wxPushMessage(Long source, PushMessage pm)throws Exception {
        String token = null;
        if (!redisClientUtils.exists(source+"ACCESSTOKEN")){
            token= getToken(source);
        }else {
            token= redisClientUtils.get(source+"ACCESSTOKEN");
        }
        WxResult result = WxUtils.wxPushMessage(pm,token);
        if (40001 == result.getErrcode()) {
            //重新获取token，继续同步工单
            result = WxUtils.wxPushMessage(pm, getToken(source));
        }
        return result;
    }


    @Override
    public Map<String,String> getOpenId(Long companyID,String code) throws Exception {

        WxAppInfo appInfo = WxUtils.getWxAppInfo(companyID.intValue());
        if (appInfo==null){
            //throw new Exception("未获取微信基础参数");
            log.error("getOpenId获取微信TOKEN失败");
            return null;
        }
        //获取微信TOKEn
        ManagementToken token = WxUtils.getTokenByCode(appInfo.getAppId(),appInfo.getSecret(),code);
        if (token== null){
            //throw new Exception("获取微信TOKEN失败");
            log.error("getOpenId获取微信TOKEN失败");
            return null;
        }
//        redisClientUtils.set(companyID+"ACCESSTOKEN",token.getAccessToken(),60*60);
        Map<String,String>  result = new HashMap<>();
        result.put("openid",token.getOpenid());
        return result;
    }
    @Override
    public Map<String, String> getJsConfig(WeChatJsConfigRequest configRequest, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {
        String token = getToken(configRequest.getSource());
        String ticket  = getWeChatJsTicket(configRequest.getCompanyID(),configRequest.getSource(),token);
        return WxUtils.getJsTicketSign(ticket,configRequest.getUrl());
    }

    private String getWeChatJsTicket(Long companyID, Long source,String token) throws Exception{
        if (redisClientUtils.exists(companyID+source+"jsTicket")){
            return redisClientUtils.get(companyID+source+"jsTicket");
        }
        JsTicket ticket =  WxUtils.getJsapiTicket(token);
        if (ticket == null){
            throw new NotCheckException(-99,"获取JSTicket失败无返回值");
        }
        else if (ticket.getErrcode()>0 || !"ok".equals(ticket.getErrmsg())){
            throw new NotCheckException(-99,ticket.getErrmsg());
        }
        else {
            redisClientUtils.set(companyID+source+"jsTicket",ticket.getTicket(),60*60);
        }
        return ticket.getTicket();
    }

}
